package com.example.sunmiv1.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;

import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.ReportLossListAdapter;
import com.example.sunmiv1.adapter.ReportLossSearchAdapter;
import com.example.sunmiv1.base.BaseChooseActivity;
import com.example.sunmiv1.entity.LossGoodsInfo;
import com.example.sunmiv1.entity.ReportLossGoodBean;
import com.example.sunmiv1.entity.ScanGoodInfo;
import com.example.sunmiv1.utils.LogUtil;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class ReportLossSearchActivity extends BaseChooseActivity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.view_bg_top)
    View viewBgTop;
    @BindView(R.id.tv_pick_sort)
    TextView tvPickSort;
    @BindView(R.id.ed_num_search)
    EditText edNumSearch;
    @BindView(R.id.iv_search_code)
    ImageView ivSearchCode;
    @BindView(R.id.iv_search)
    ImageView ivSearch;
    @BindView(R.id.view_bg_footer)
    View viewBgFooter;
    @BindView(R.id.btn_checkall)
    Button btnCheckall;
    @BindView(R.id.btn_add_to_list)
    Button btnAddToList;
    @BindView(R.id.rv_goods_choose)
    RecyclerView rvGoodsChoose;
    @BindView(R.id.btn_ok)
    Button btnOk;
    @BindView(R.id.btn_checkall_not)
    Button btnCheckallNot;
    @BindView(R.id.btn_to_top)
    ImageView btnToTop;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;

    private ReportLossSearchAdapter adapter;
    private LossGoodsInfo lossGoodsInfo;
    private List<LossGoodsInfo.DataBean> dataList;
    private ArrayList<LossGoodsInfo.DataBean> choiceList; // 回傳參數列表

    @SuppressLint("HandlerLeak")// todo:可能有內存泄漏，待優化
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    progressBar.setVisibility(View.GONE);
                    setAdapter();
                    break;
                case 2:
                    setAdapter();
                    break;
                case GET_ERROR_STATUS:
                    break;
            }
        }
    };

    @Override
    protected void initChoiceList() {
        dataList = new ArrayList<>();
        choiceList = new ArrayList<>();
        btnAddToList.setText(R.string.addReportLossList);
    }

    /* 添加到回傳列表中，並且移除當前頁面*/
    protected void addToListAndRemove() {
        for (int i = dataList.size() - 1; i >= 0; i--) {
            if (dataList.get(i).isChecked()) {
                notInIdArr.add(dataList.get(i).getId());
                adapter.notifyItemRemoved(i);
                choiceList.add(dataList.remove(i));
            }
        }
        if (dataList.size() == 0) {
            page++;
            getListInfo(page);
        }
    }

    /* 直接添加到回傳列表*/
    protected void addToList() {
        for (int i = dataList.size() - 1; i >= 0; i--) {
            if (dataList.get(i).isChecked()) {
                choiceList.add(dataList.remove(i));
            }
        }

    }

    @Override
    protected void setAdapter() {
        if (adapter == null) {
            adapter = new ReportLossSearchAdapter(ReportLossSearchActivity.this, dataList);
            rvGoodsChoose.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
        adapter.setChoose(index -> {
            Intent intent = new Intent(context, StringCodeOperationActivity.class);
            intent.putExtra("operation", 5);
            intent.putExtra("good", dataList.get(index));
            startActivityForResult(intent, 200);
        });
    }

    @Override
    protected void getListInfo(int page) {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        String url = "";
        try {
            jsonObject.put("page", page);
            jsonObject.put("limit", limit);
            jsonObject.put("user_type", aCache.getAsString("userType"));
            jsonObject.put("person1", category[0]);//一級分類id
            jsonObject.put("person2", category[1]);//二級分類id
            jsonObject.put("person3", category[2]);//三級分類id
            jsonObject.put("exists_id_arr", toNotInIds(notInIdArr));
            jsonObject.put("searchText", edNumSearch.getText().toString().trim());
//            if ("2".equals(aCache.getAsString("userType"))) {
//                url = Common.STORE_LOSS_GOODS_LIST;
//            } else if ("1".equals(aCache.getAsString("userType"))) {
//                url = Common.LOSS_GOODS_LIST;
//            } else {
                url = Common.STORE_LOSS_GOODS_LIST;
//            }
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(this, url, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    Gson gson = new Gson();
                    lossGoodsInfo = gson.fromJson(text, LossGoodsInfo.class);
                    if (lossGoodsInfo.getStatus() == 1) {
                        Toast.makeText(ReportLossSearchActivity.this, lossGoodsInfo.getMsg(), Toast.LENGTH_SHORT).show();
                        if (page == 1) {
                            dataList.clear();
                        }
                        dataList.addAll(lossGoodsInfo.getData());
                        mHandler.sendEmptyMessage(1);

                    } else {
                        Toast.makeText(ReportLossSearchActivity.this, lossGoodsInfo.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                    loadingDialog.dismiss();
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.title_back, R.id.btn_to_top, R.id.title_title, R.id.tv_pick_sort, R.id.iv_search_code, R.id.iv_search,
            R.id.btn_checkall, R.id.btn_checkall_not, R.id.btn_add_to_list, R.id.btn_ok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                putExtra(this, NewReportLossActivity.class, choiceList, "");
                break;
            case R.id.iv_search_code:  // 調起掃碼
                startQrCode();
                break;
            case R.id.iv_search:
                LogUtil.i("searchText:" + edNumSearch.getText().toString().trim());
                getListInfo(1);
                break;
            case R.id.btn_checkall:  // 全選操作
                btnCheckall.setVisibility(View.GONE);
                btnCheckallNot.setVisibility(View.VISIBLE);
                adapter.checkAll();
                break;
            case R.id.btn_checkall_not: // 全不選操作
                adapter.checkAllNot();
                btnCheckallNot.setVisibility(View.GONE);
                btnCheckall.setVisibility(View.VISIBLE);
                break;
            case R.id.btn_add_to_list:  //添加到上頁列表中
                addToListAndRemove();
                break;
            case R.id.btn_ok:  //添加到上頁列表並返回
                addToList();
                putExtra(this, NewReportLossActivity.class, choiceList, "");
                break;
            case R.id.tv_pick_sort:  //分類篩選
                if (classificationBean != null && classificationBean.getStatus() == 1 && classificationBean.getGoodscate().size() > 0) {
//                    showPickerView(options1Items, options2Items, options3Items, classificationBean);
                    showPickerView();
                } else {
                    Toast.makeText(this, "無法獲取分類列表", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_to_top:
                rvGoodsChoose.smoothScrollToPosition(0);
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + view.getId());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 200:
                    LossGoodsInfo.DataBean bean = (LossGoodsInfo.DataBean) data.getSerializableExtra("bean");
                    int index = 0;
                    for (int t = 0; t < dataList.size(); t++) {
                        if (bean.getGoods_id().equals(dataList.get(t).getGoods_id())) {
                            if ("2".equals(bean.getAttribute_state())) {
                                if (bean.getSku_id().equals(dataList.get(t).getSku_id())) {
                                    index = t;
                                    break;
                                }
                            } else {
                                index = t;
                                break;
                            }
                        }
                    }
                    dataList.set(index, bean);
                    setAdapter();
                    break;
            }
        }

    }

    @Override
    public void getInfo(String tvShowText) {
        super.getInfo(tvShowText);
        tvPickSort.setText(tvShowText);
        getListInfo(1);
    }
}
